package com.singbon.server.security;
import com.singbon.server.pojo.AuthGroup;
import com.singbon.server.pojo.AuthgroupUser;
import com.singbon.server.pojo.SysUser;
import com.singbon.server.service.AuthGroupService;
import com.singbon.server.service.AuthGroupUserService;
import com.singbon.server.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 */
@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
  @Resource
  private SysUserService userService;
  @Resource
  private AuthGroupService roleService;
  @Resource
  private AuthGroupUserService userRoleService;
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    // 从数据库中取出用户信息
    SysUser user = userService.selectByName(username);
    // System.out.println("user = " + user)
    // 判断用户是否存在
    if (user == null) {
      log.warn("user dose not exit:username:{}", username);
      throw new UsernameNotFoundException("用户名不存在");
    }
    // 添加权限
    List<AuthgroupUser> userRoles = userRoleService.listByUserId(user.getOperId());
    AuthGroup role = null;
    for (AuthgroupUser userRole : userRoles) {
      role = roleService.selectById(userRole.getGroupid());
    }
    if (role == null) {
      throw new UsernameNotFoundException("用户没有权限");
    }
    // 返回UserDetails实现类
    return new User(user.getLoginName(), user.getLoginPwd(), AuthorityUtils.commaSeparatedStringToAuthorityList(role.getRoles()));
  }
}
